package com.simtop.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.simtop.common.ServerResponse;
import com.simtop.pojo.userpo.User;
import com.simtop.pojo.experimentpo.Experiment;
import com.simtop.pojo.experimentpo.ExperimentDynamicVo;
import com.simtop.pojo.experimentpo.ExperimentReportVo;
import com.simtop.service.ExperimentService;
import com.simtop.util.jwtutil.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author: liuzhaobo
 * @Description: 实验报告
 * @DateTime: 2022/8/31 0031 16:53
 * @Params:
 * @Return
 */
@CrossOrigin
@RestController
@RequestMapping("/experiment")
public class ExperimentController {

    @Autowired
    private ExperimentService experimentService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 点赞存储的键名
     */
    private static final String KEY = "editorCheck:giveLike:";


    /**
     * 提交成绩
     *
     * @param experiment
     * @param request
     * @return
     */
    @PostMapping("/add")
    public ServerResponse add(@RequestBody Experiment experiment, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        try {
            experiment.setUserId(u.getId());
            boolean flag = experimentService.insertExperiment(experiment);
            if (flag == false) {
                return ServerResponse.createByErrorMsg("提交内容失败");
            }
            return ServerResponse.createBySuccessMsg("提交内容成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMsg("提交内容失败");
        }
    }

    /**
     * 修改提交内容
     *
     * @param experiment
     * @param request
     * @return
     */
    @PostMapping("/update")
    public ServerResponse update(@RequestBody Experiment experiment, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        try {
            experimentService.updateExperiment(experiment);
            return ServerResponse.createBySuccessMsg("修改成绩成功");
        } catch (Exception e) {
            return ServerResponse.createByErrorMsg("修改成绩失败");
        }
    }

    /**
     * 查看实验动态(即每个人都能看到其他所有人)
     *
     * @param experimentDynamicVo
     * @param request
     * @return
     */
    @PostMapping("/getDynamic")
    public ServerResponse getDynamic(@RequestBody ExperimentDynamicVo experimentDynamicVo, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        try {
            PageHelper.startPage(experimentDynamicVo.getPageNum(), experimentDynamicVo.getPageSize());
            List<ExperimentDynamicVo> allDynamic = experimentService.getAllDynamic(experimentDynamicVo.getMessage());
            allDynamic.forEach(
                    a -> {
                        //拿到 点赞从次数
                        a.setGiveLike(redisTemplate.opsForSet().size(KEY + a.getExperimentId()));
                        // 是否点赞
                        a.setIfGiveLike(redisTemplate.opsForSet().isMember(KEY + a.getExperimentId(), u.getId()));
                    }
            );
            PageInfo<ExperimentDynamicVo> pageInfo = new PageInfo<>(allDynamic);
            return ServerResponse.createBySuccess("获取动态成功", pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMsg("获取动态失败");
        }
    }



    /**
     * 点赞
     */
    @PostMapping("/giveLike")
    public ServerResponse giveLike(@RequestBody String data, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        try {
            JSONObject jsonObject = JSONObject.parseObject(data);
            Long id = jsonObject.getLong("experimentId");
            redisTemplate.opsForSet().add(KEY + id, u.getId());
            return ServerResponse.createBySuccessMsg("点赞成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMsg("点赞失败");
        }
    }


    /**
     * 删除实验报告
     */
    @PostMapping("/delete")
    public ServerResponse delete(@RequestBody String data, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        try {
            JSONObject jsonObject = JSONObject.parseObject(data);
            Long id = jsonObject.getLong("experimentId");
            experimentService.delete(id);
            return ServerResponse.createBySuccessMsg("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMsg("删除失败");
        }
    }
}